/*
 * @Author: 谢陈洁
 * @Date: 2025-05-26 10:24:39
 * @LastEditors: 谢陈洁
 * @LastEditTime: 2025-06-06 09:28:10
 * @Description: file content
 */
import { ElMessage } from 'element-plus'
import service from './index'
import type { AxiosProgressEvent } from 'axios'

// 定义通用响应类型
export interface ApiResponse<T> {
  code: number
  message?: string
  data: T
}

// 通用请求封装（可选：统一错误处理、拦截器扩展）
async function request<T>(
  method: 'get' | 'post' | 'put' | 'delete',
  url: string,
  options: Record<string, any> = {}
): Promise<ApiResponse<T>> {
  try {
    const axiosConfig = {
      method,
      url,
      ...options
    }
    const response = await service(axiosConfig)
    const { code, data } = response.data
    console.log('请求响应数据：', response, data, options)
    if (code !== 200) {
      // 处理业务错误
      ElMessage.error(data?.message || '请求失败：未知错误')
    }
    return data
  } catch (error: any) {
    // 统一错误处理逻辑（可根据业务需求扩展）
    let message = '请求失败'
    if (error.response) {
      // 请求已发出，服务器以状态码响应（非 2xx）
      message = error.response.data?.message || `HTTP Error ${error.response.status}`
    } else if (error.request) {
      // 请求已发出但无响应
      message = '无响应，请检查网络连接'
    } else {
      // 其他错误
      message = error.message
    }
    throw new Error(message)
  }
}

// 封装GET请求
// export function get<T = any>(url: string, params?: Record<string, any>): Promise<ApiResponse<T>> {
export function get(url: string, params?: Record<string, any>): Promise<any> {
  return request('get', url, { params })
}

// 封装POST请求
export function post<T, D extends Record<string, unknown>>(
  url: string,
  data?: D,
  config?: Record<string, unknown>
): Promise<ApiResponse<T>> {
  console.log('POST请求的URL:', url, '数据:', data)
  return request('post', url, { ...config, data })
}

// 封装PUT请求
export function put<T>(url: string, data?: Record<string, any>): Promise<ApiResponse<T>> {
  return request('put', url, { data })
}

// 封装DELETE请求
export function del<T>(url: string): Promise<ApiResponse<T>> {
  return request('delete', url)
}

// 文件上传方法
export function upload<T>(
  url: string,
  formData: FormData,
  onUploadProgress?: (progressEvent: AxiosProgressEvent) => void
): Promise<ApiResponse<T>> {
  return service.post(url, formData, {
    headers: { 'Content-Type': 'multipart/form-data' },
    onUploadProgress
  })
}
